package com.nd.android.musicboxlibrary.interf.impl;

import android.content.Context;
import android.os.Looper;

import com.nd.android.musicboxlibrary.GlobalSetting;
import com.nd.android.musicboxlibrary.business.bean.Album;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.ApiManager;
import com.nd.android.musicboxlibrary.business.comm.BusProvider;
import com.nd.android.musicboxlibrary.business.comm.MenuPositionEvent;
import com.nd.android.musicboxlibrary.business.comm.NdException;
import com.nd.android.musicboxlibrary.interf.IPlaylistManager;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.vip.VipUtil;
import com.nd.android.musicboxlibrary.util.ConfigHelper;

import java.util.List;

/**
 * <br>
 * Created 2014年7月11日 下午10:56:24
 * 
 * @author wat.ztag
 * @see
 */
public class PlaylistManager implements IPlaylistManager {
	private Context mContext;
	
	/** 当前是否正在网络加载音乐信息数据 */
	//public boolean isLoadingMusicList = true;
	
	/** 当前音乐信息数据是否全部下载完成了*/
	public boolean isLoadedMusicList = false;
	

	/**
	 * Creates a new instance of PlaylistManager. <br>
	 * Created 2014年9月15日 下午11:15:24
	 * @param context Context
	 */
	public PlaylistManager(Context context) {
		mContext = context;
	}

	@Override
	public MusicInfo findMusic(long id) {
		return ApiManager.getInstance(mContext).getDb().findMusic(id);
	}

	@Override
	public List<MusicInfo> getMusicListOfFav() {
		// 上传本地喜欢歌曲到服务端
		// 取服务端我喜欢歌曲，更新本地缓存
		// try {
		//
		// ApiManager.getInstance(mContext).setMusicFav(musicInfo.getId(), true);
		//
		// // 判断是否打开自动下载开关，有打开的话，需加入下载列表
		// if (ConfigHelper.getInstance().loadBooleanKey(
		// ConfigHelper.CONFIG_KEY_AUTO_DOWNLOAD, false)) {
		// ManagerFactory.getDownloadInstance(mContext).addMusic2DownloadList(musicInfo);
		// }
		// } catch (NdException e) {
		// e.printStackTrace();
		// }
		// 从本地取我喜欢歌曲列表
		return ApiManager.getInstance(mContext).getDb()
				.getMusicListOfFav(GlobalSetting.MUSIC_FAV_LIST_MAX);
	}

	@Override
	public List<MusicInfo> getMusicListOfDownLoad() {
		return ApiManager.getInstance(mContext).getDb().getMusicListOfDownLoad();
	}

	@Override
	public List<MusicInfo> getMusicListOfLastPlayed() {
		return ApiManager.getInstance(mContext).getDb()
				.getMusicListOfLastPlayed(GlobalSetting.MUSIC_LIST_MAX_LASTPLAYED);
	}

	@Override
	public List<MusicInfo> getMusicList()  {
		isLoadedMusicList = false;
		List<MusicInfo> result = ApiManager.getInstance(mContext).getDb().getMusicList();
		try {
			if (result.isEmpty()) {//如果，数据没有全部下载完成，那这个result就不为空了,bug啊bug怎么破 -- BUG #63906 
				result = ApiManager.getInstance(mContext).getMusicList();

				ApiManager.getInstance(mContext).getDb().setMusicList(result);
			} else if (!ConfigHelper.getInstance(mContext).loadBooleanKey(ConfigHelper.CONFIG_LRC_UTF, false)) {
				// 历史版本处理，判断歌词格式是否为UTF8，若不是的话重新下载歌词
				ManagerFactory.getDownloadInstance(mContext).batchAddLrc2DownloadList(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			isLoadedMusicList = true;
		}
		return result;
	}

	@Override
	public List<MusicInfo> searchMusicList(String kewWord) {
		return ApiManager.getInstance(mContext).getDb().searchMusicList(kewWord);
	}

	@Override
	public List<Album> getAlbumList() throws NdException {
		List<Album> result = ApiManager.getInstance(mContext).getDb().getAlbumList();
		if (result.isEmpty()) {
			result = ApiManager.getInstance(mContext).getAlbumList();

			try {
				ApiManager.getInstance(mContext).getDb().setAlbumList(result);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	@Override
	public List<MusicInfo> getMusicListOfAlbum(long ablumId) {
		if(Looper.myLooper() != Looper.getMainLooper()){
			//如果当前，不是主线程，那么就不会出现RNS，不会出现等待超时异常。
			//这个逻辑，主要是等待网络数据请求完成，才能好好的显示出歌曲数据
			//起到缓冲等待的作用
			//by jiangwb
			while(!isLoadedMusicList){}			
		}
		return ApiManager.getInstance(mContext).getDb().getMusicListOfAlbum(ablumId);
	}

	@Override
	public List<MusicInfo> getMusicListOfPlaying() {
		List<MusicInfo> result = ApiManager.getInstance(mContext).getDb()
				.getMusicListOfPlaying(GlobalSetting.MUSIC_LIST_MAX);
		return result;
	}

	@Override
	public void likeMusic(final MusicInfo musicInfo) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ApiManager.getInstance(mContext).getDb().likeMusic(musicInfo.getId());
					List<MusicInfo> list = getMusicListOfPlaying();
					if (list != null && !list.isEmpty() && list.contains(musicInfo)) {
						ManagerFactory.getPlayerInstance().initMusicList(mContext);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					// 判断是否打开自动下载开关，有打开的话，需加入下载列表
					if (ConfigHelper.getInstance(mContext).loadBooleanKey(
							ConfigHelper.CONFIG_KEY_AUTO_DOWNLOAD, false)) {
						if(VipUtil.isVip() && musicInfo.getHQId() > 0){
							//by jiangwb 如果是vip用户，同时歌曲有HQ版本，就自动下载HQ文件
							musicInfo.setHQ(true);
						}
						ManagerFactory.getDownloadInstance(mContext).addMusic2DownloadList(
								musicInfo, musicInfo.isHQ());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				try {
					ApiManager.getInstance(mContext).setMusicFav(musicInfo.getId(), true);

				} catch (NdException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@Override
	public void unLikeMusic(final MusicInfo musicInfo) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ApiManager.getInstance(mContext).getDb().unLikeMusic(musicInfo.getId());
					List<MusicInfo> list = getMusicListOfPlaying();
					if (list != null && !list.isEmpty() && list.contains(musicInfo)) {
						ManagerFactory.getPlayerInstance().initMusicList(mContext);
					}
					ApiManager.getInstance(mContext).setMusicFav(musicInfo.getId(), false);
				} catch (NdException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	@Override
	public void replaceMusicListOfPlaying(final List<? extends MusicInfo> musicInfoList) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ApiManager.getInstance(mContext).getDb()
					.replaceMusicListOfPlaying(musicInfoList);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();

	}

	@Override
	public void addMusic2LastPlayed(final MusicInfo musicInfo) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ApiManager.getInstance(mContext).getDb().addMusic2LastPlayed(musicInfo.getId());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

}
